using System;
using System.Collections.Generic;
using Entity;
using Utils;

namespace Mapper
{
    class DeckMapper
    {

        private const string TABLE_NAME = "deck";
        public DeckMapper()
        {
            MySQLUtil.CreateConnection();
        }

        public List<Deck> GetAllDecks()
        {
            return MySQLUtil.SelectData<Deck>(TABLE_NAME, "*", null);
        }

        public Deck GetDeckByDeckId(long deckId)
        {
            return MySQLUtil.SelectData<Deck>(TABLE_NAME, "*", "cardId = " + deckId)[0];
        }

        public List<Deck> GetAllDecksByUserId(long userId)
        {
            return MySQLUtil.SelectData<Deck>(TABLE_NAME, "*", "userId = " + userId);
        }

        public void DeleteCardFromDeckByCardId(long deckId, long cardId)
        {
            string sql = $"delete from deck_card_rel where deckId = {deckId} and cardId = {cardId}";
            MySQLUtil.UpdateData(sql);
        }

        public void DeleteAllCardsFromDeckByDeckId(long deckId)
        {
            string sql = $"delete from deck_card_rel where deckId = {deckId}";
            MySQLUtil.UpdateData(sql);
        }

        public void AddCardToDeck(long deckId, long cardId , long cardCount)
        {
            string sql = $"insert into deck_card_rel (deckId , cardId , cardCount) values ( {deckId}, {cardId} , {cardCount})";
            MySQLUtil.UpdateData(sql);
        }

        public void CloseConnection()
        {
            MySQLUtil.Close();
        }

        internal List<Deck> GetDecksPageByUserId(int userId, int current, int pageSize)
        {
            int start = (current - 1) * pageSize;
            int end = current * pageSize;
            return MySQLUtil.SelectData<Deck>($"select * from deck where userId = {userId} limit {start} , {end}");
        }
    }
}

